package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/lab-online/internal/class/constant"
	"github.com/lab-online/internal/class/entity"
	"github.com/lab-online/pkg/auth"
	mw "github.com/lab-online/pkg/middleware"
	"github.com/lab-online/pkg/resp"
)

type UpdateClassReqParam struct {
	ClassID uint `uri:"id" binding:"required" example:"1"` // 班级ID
}

type UpdateClassReqBody struct {
	Name        string `json:"name" binding:"required,min=1,max=20" example:"高等数学"`               // 班级名称
	Description string `json:"description" binding:"required,min=1,max=100" example:"这是一门很有趣的课程"` // 班级介绍
}

var UpdateClassValidator = mw.NewValidator(func() *mw.ValidatorOptions {
	return &mw.ValidatorOptions{
		Params: &UpdateClassReqParam{},
		Body:   &UpdateClassReqBody{},
	}
})

type UpdateClassRespBody struct {
	resp.BaseRespBody
}

// UpdateClass 更新班级
//
//	@Summary				更新班级
//	@Description			教师可以更新自己班级的信息，管理员可以更新任何班级的信息，可更新的信息有：班级名称、班级介绍
//	@Description.markdown	UpdateClass
//	@Tags					class
//	@Accept					json
//	@Produce				json
//	@Security				bearer
//	@Param					Authorization	header		string				true	"`teacher` | `admin`"
//	@Param					class			path		string				true	"班级ID"
//	@Param					class			body		UpdateClassReqBody	true	"更新信息"
//	@Success				201				{object}	UpdateClassRespBody
//	@Failure				400				{object}	resp.FailedRespBodyString
//	@Failure				403				{object}	resp.FailedRespBodyString
//	@Failure				500				{object}	resp.FailedRespBodyString
//	@x-apifox-status		"developing"
//	@Router					/v1/class/:classID	[put]
func (h *Handler) UpdateClass(c *gin.Context) {
	classID := c.MustGet(mw.KeyParams).(*UpdateClassReqParam).ClassID
	authEntity := c.MustGet(auth.KeyAuth).(auth.AuthEntity)
	updateInfo := c.MustGet(mw.KeyBody).(*UpdateClassReqBody)

	classEntity := entity.NewClassEntity(
		entity.WithID(classID),
		entity.WithName(updateInfo.Name),
		entity.WithDescription(updateInfo.Description),
	)

	if err := h.domain.UpdateClass(classEntity, authEntity); err != nil {
		resp.ErrorHandler(c, err)
	} else {
		resp.Success[any](c, constant.CodeUpdateClassSuccess)
	}
}
